//
//  JLRegisterViewController.m
//  JLStyleApp
//
//  Created by LvJianfeng on 15/8/18.
//  Copyright (c) 2015年 JLStyle. All rights reserved.
//

#import "JLRegisterViewController.h"
#import "JLVerifyCodeViewController.h"

@interface JLRegisterViewController () <UIScrollViewDelegate, UITextFieldDelegate>
{
    UIButton *doneInKeyboardButton;
    BOOL keyboardIsVisible;
}
@property (strong, nonatomic) UIScrollView *scrollview;

//两个文本框
@property (weak, nonatomic) UITextField *phoneTextView;
@property (weak, nonatomic) UITextField *passTextView;

@property (strong, nonatomic) UIButton *registerButton;
@end

@implementation JLRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    keyboardIsVisible = YES;
    self.title = @"注册";
    self.view.backgroundColor = [UIColor customControllerBackgroundColor];
    [self.view addSubview:self.scrollview];
    //配置
    [self setupRegisterView];
    //按钮
    [self.scrollview addSubview:self.registerButton];
}
//注册
- (void)registerAction:(UIButton *)sender{
    //失去焦点
    [self.phoneTextView resignFirstResponder];
    [self.passTextView resignFirstResponder];
    if (isNullString(self.phoneTextView.text) || ![JFGlobalInstance validateNumber:self.phoneTextView.text]) {
        [self.phoneTextView becomeFirstResponder];
        return;
    }
    if (isNullString(self.passTextView.text)) {
        [self.passTextView becomeFirstResponder];
        return;
    }
    [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    //区域
    NSString* areaCode = [AreaCode stringByReplacingOccurrencesOfString:@"+" withString:@""];
    //发送验证码
    [SMS_SDK getVerificationCodeBySMSWithPhone:self.phoneTextView.text zone:areaCode result:^(SMS_SDKError *error) {
        if (!error) {
            [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
            JLVerifyCodeViewController *verifyCodeViewController = [[JLVerifyCodeViewController alloc] init];
            verifyCodeViewController.phone = self.phoneTextView.text;
            verifyCodeViewController.password = self.passTextView.text;
            [self.navigationController pushViewController:verifyCodeViewController animated:YES];
        }else{
            [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
            [JFGlobalInstance showAlertLabel:self.navigationController.view text:@"(%>_<%)验证码发送错误了,会不会太平凡了" afterDelay:2.f];
        }
    }];
}

//键盘
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setCustomBackgroundColor:GlobalColor];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
}

//退出时移除观察者
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.phoneTextView resignFirstResponder];
}

#pragma mark 键盘消息方法
- (void)keyboardWillShow:(NSNotification*)aNotification
{
    //判断doneInKeyboardButton==nil
    if (doneInKeyboardButton==nil && ![self.passTextView becomeFirstResponder]) {
        [self configDoneInKeyBoardButton];
    }
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    if (doneInKeyboardButton) {
        [doneInKeyboardButton removeFromSuperview];
        doneInKeyboardButton = nil;
        //让手机号输入框失去第一响应,确保每一响应都会去创建确认按钮
        [self.phoneTextView resignFirstResponder];
    }

}

//拖动将结束
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    keyboardIsVisible = YES;
    [self.view endEditing:YES];
}

//配置界面
- (void)setupRegisterView{
    //文本框
    UITextField *phoneTextView = [[UITextField alloc] init];
    phoneTextView.delegate = self;
    phoneTextView.placeholder = @"手机号码";
    phoneTextView.backgroundColor = [UIColor whiteColor];
    phoneTextView.textColor = [UIColor customLightPlaceColor];
    phoneTextView.font = JLBlodFont(16);
    phoneTextView.keyboardType = UIKeyboardTypeNumberPad;
    phoneTextView.returnKeyType = UIReturnKeyDone;
    phoneTextView.clearButtonMode = UITextFieldViewModeWhileEditing;
    phoneTextView.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
    phoneTextView.leftViewMode = UITextFieldViewModeAlways;
    phoneTextView.frame = CGRectMake(0, 20, ScreenWidth, 50);
    [self.scrollview addSubview:phoneTextView];
    self.phoneTextView = phoneTextView;
    
    //文本框
    UITextField *passTextView = [[UITextField alloc] init];
    passTextView.delegate = self;
    passTextView.placeholder = @"密码";
    passTextView.backgroundColor = [UIColor whiteColor];
    passTextView.textColor = [UIColor customLightPlaceColor];
    passTextView.font = JLBlodFont(16);
    passTextView.returnKeyType = UIReturnKeyDone;
    passTextView.clearButtonMode = UITextFieldViewModeWhileEditing;
    passTextView.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
    passTextView.leftViewMode = UITextFieldViewModeAlways;
    passTextView.frame = CGRectMake(0, 20+51, ScreenWidth, 50);
    [self.scrollview addSubview:passTextView];
    self.passTextView = passTextView;
}

#pragma mark - textField Delegate

//Return
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField == self.phoneTextView) {
        //让密码输入框成为第一响应者
        [self.passTextView becomeFirstResponder];
    }else{
        [textField resignFirstResponder];
    }
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == self.phoneTextView) {
        //创建确认键
        [self configDoneInKeyBoardButton];
    }else{
        [doneInKeyboardButton removeFromSuperview];
        doneInKeyboardButton = nil;
    }
}
- (void)configDoneInKeyBoardButton{
    //初始化
    if (doneInKeyboardButton == nil)
    {
        doneInKeyboardButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [doneInKeyboardButton setTitle:@"确认" forState:UIControlStateNormal];
        [doneInKeyboardButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        doneInKeyboardButton.adjustsImageWhenHighlighted = NO;
        [doneInKeyboardButton addTarget:self action:@selector(finishAction) forControlEvents:UIControlEventTouchUpInside];
    }
    //每次必须从新设定“确认”按钮的初始化坐标位置
    doneInKeyboardButton.frame = CGRectMake(0, ScreenHeight+216, 122, 53);
    
    //由于ios8下，键盘所在的window视图还没有初始化完成，调用在下一次 runloop 下获得键盘所在的window视图
    [self performSelector:@selector(addDoneButton) withObject:nil afterDelay:0.0f];
}
#pragma mark -实现事件
- (void) addDoneButton{
    //获得键盘所在的window视图
    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    [tempWindow addSubview:doneInKeyboardButton];// 注意这里直接加到window上
    
    if (keyboardIsVisible) {
        [UIView animateWithDuration:0.25 delay:0.0 options:7 << 16 animations:^{
            doneInKeyboardButton.transform = CGAffineTransformMakeTranslation(0, -269);
        } completion:^(BOOL finished) {
            keyboardIsVisible = NO;
        }];
    }else{
        doneInKeyboardButton.frame = CGRectMake(0, ScreenHeight-53, 106, 53);
    }
    
    
}
-(void)finishAction{
    [self.passTextView becomeFirstResponder];
}

#pragma mark-textField的代理
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField{
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    //你的每一次输入的都会执行到这里
    return YES;
}

#pragma mark lazyload

- (UIButton *)registerButton{
    if (_registerButton==nil) {
        CGFloat registerButtonW = ScreenWidth-40;
        _registerButton = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth/2-registerButtonW/2, self.passTextView.center.y+25+50, registerButtonW, 50)];
        _registerButton.titleLabel.textColor = [UIColor whiteColor];
        _registerButton.backgroundColor = GlobalColor;
        _registerButton.titleLabel.font = JLBlodFont(18);
        _registerButton.layer.cornerRadius = 25;
        [_registerButton setTitle:@"注册" forState:UIControlStateNormal];
        
        [_registerButton addTarget:self action:@selector(registerAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _registerButton;
}

-(UIScrollView *)scrollview{
    if (_scrollview==nil) {
        _scrollview = [[UIScrollView alloc] initWithFrame:self.view.bounds];
        _scrollview.showsVerticalScrollIndicator = NO;
        _scrollview.showsHorizontalScrollIndicator = NO;
        _scrollview.delegate = self;
    }
    return _scrollview;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
